package com.rpp.study.filter;

import com.rpp.study.config.UserConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashSet;
import java.util.Set;

/**
 * @Description
 * @Author rpp
 * @Date 2020/8/30 20:19 下午
 */
@Slf4j
@Component
public class TokenFilter implements GlobalFilter, Ordered {

    // 不需要token校验的接口
    private static final Set<String> whiteUri = new HashSet<String>() {
        {
            add("/api/user/login");
            add("/api/user/register");
            add("/api/user/isRegistered");
            add("/api/code/create");
        }
    };

    /**
     * 过滤器核心方法
     *
     * @param exchange 封装了request和response对象的上下文
     * @param chain    网关过滤器链（包含全局过滤器和单路由过滤器）
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        String path = request.getURI().getPath();
        String[] split = path.split("/");
        String key = new StringBuilder("/").append(split[1]).append("/").append(split[2])
                .append("/").append(split[3]).toString();
        if (!whiteUri.contains(key)) {
            MultiValueMap<String, HttpCookie> cookies = request.getCookies();
            HttpCookie cookie = cookies.getFirst(UserConfig.COOKIE_NAME);
            if (null == cookie) {
                log.info("token校验不通过，path:{}", path);
                //303状态码表示由于请求对应的资源存在着另一个URI，应使用GET方法定向获取请求的资源
                response.setStatusCode(HttpStatus.SEE_OTHER);
                response.getHeaders().set(HttpHeaders.LOCATION, "http://www.test.com/static/login.html");
                response.getHeaders().add("Content-Type", "text/plain;charset=UTF-8");
                return response.setComplete();

            }
        }

        // 合法请求，放行，执行后续的过滤器
        return chain.filter(exchange);
    }


    /**
     * 返回值表示当前过滤器的顺序(优先级)，数值越小，优先级越高
     *
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
